package com.alameda.common.commonpent.lock.impl;

import com.alameda.common.commonpent.lock.api.DistributedLockTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * zookeeper 分布式锁组件 具体实现
 *
 * @author Lv
 * @date 2024/8/3
 */
@Slf4j
@Component
public class DistributedLockTemplateImpl implements DistributedLockTemplate {

    private final CuratorFramework curatorFramework;

    private final InterProcessMutex lock;

    /**
     * 注入curator 实例
     *
     * @param curatorFramework curator zk操作对象
     */
    @Autowired
    public DistributedLockTemplateImpl(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
        this.lock = new InterProcessMutex(curatorFramework, "/distributed-lock");
    }

    /**
     * 添加分布式锁
     */
    @Override
    public void acquireLock() {
        acquireLock(3, TimeUnit.SECONDS);
    }

    /**
     * 添加分布式锁
     *
     * @param time     锁时间长度
     * @param timeUnit 时间类型
     */
    @Override
    public void acquireLock(int time, TimeUnit timeUnit) {
        // 检查连接状态
        boolean connected = curatorFramework.getZookeeperClient().isConnected();
        if (connected) {
            try {
                // 加锁
                lock.acquire(time, timeUnit);
                log.info("加锁成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放锁
     */
    @Override
    public void releaseLock() {
        // 检查连接状态
        boolean connected = curatorFramework.getZookeeperClient().isConnected();
        if (connected) {
            try {
                lock.release();
                log.info("释放锁成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
